package knapsackga;

public class FitnessFunctionA implements FitnessFunction
{
    private Knapsack _knapsack;

    public FitnessFunctionA( Knapsack knapsack )
    {
        _knapsack = knapsack;
    }

    public double calculateFitness( int[] alleles )
    {
        double fitness = 0;

        int weight = _knapsack.getMaxWeight();
        int value = 0;

        /*
         * figure out the weight "remaining" after packing the knapsack and
         * value of what we've put in it
         */
        for( int i = 0; i < alleles.length; i++ )
        {
            if( alleles[i] == 1 )
            {
                KnapsackObject object = _knapsack.getObject( i );
                weight -= object.weight;
                value += object.value;
            }
        }

        if( weight >= 0 )
        {
            /*
             * if weight >= 0 then we haven't gone over weight so just use the
             * value of everything in the sack
             */
            fitness = value;
        }
        else
        {
            /*
             * we are over weight, so the fitness will be negative by the amount
             * we have gone over weight
             */
            fitness = weight;
        }

        return fitness;
    }
}
